package com.coastline.fruit.common.thread;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;

/**
 * 创建线程池管理类 避免创建重复线程池
 *
 * @author Coastline
 * @date 2025/1/10 22:42
 */
public class CoastlineThreadPoolManager {
    private static Map<String, ThreadPoolExecutor> threadPoolExecutorMap = new ConcurrentHashMap<>();

    /**
     * 创建线程池
     *
     * @param threadPoolName 线程池名称
     * @param corePoolSize 核心线程数
     * @param maxPoolSize 最大线程数
     * @param keepAliveTime 存活时间
     * @param workQueue 等待队列
     * @param threadFactory 线程工厂
     * @param handler 拒绝策略
     * @return threadPoolExecutor 线程池执行器
     */
    public static synchronized ThreadPoolExecutor createThreadPool(String threadPoolName, int corePoolSize, int maxPoolSize, int keepAliveTime,
                                                                   BlockingDeque<Runnable> workQueue, ThreadFactory threadFactory,
                                                                   RejectedExecutionHandler handler) {
        if (threadPoolExecutorMap.containsKey(threadPoolName)) {
            return threadPoolExecutorMap.get(threadPoolName);
        }
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, threadFactory, handler);
        threadPoolExecutorMap.put(threadPoolName, threadPoolExecutor);
        return threadPoolExecutor;
    }

    /**
     * 创建一个定时任务的线程池执行器
     *
     * @param threadPoolName 线程池名称
     * @param corePoolSize 核心线程数
     * @param threadFactory 线程池工厂
     * @param handler 拒绝策略
     * @return threadPoolExecutor 线程池执行器
     */
    public static synchronized ScheduledThreadPoolExecutor createThreadPool(String threadPoolName, int corePoolSize, ThreadFactory threadFactory,
                                                                            RejectedExecutionHandler handler) {
        if (threadPoolExecutorMap.containsKey(threadPoolName)) {
            throw new DuplicatedThreadPoolException(threadPoolName + " already exists!");
        }
        ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(corePoolSize, threadFactory, handler);
        threadPoolExecutorMap.put(threadPoolName, threadPoolExecutor);
        return threadPoolExecutor;
    }

    /**
     * 获取线程池名称
     *
     * @return set 线程池名称集合
     */
    public static Set<String> getAllThreadPoolName() {
        return threadPoolExecutorMap.keySet();
    }

    /**
     * 获取指定名称的线程池
     *
     * @param threadPoolName 线程池名称
     * @return ThreadPoolExecutor 线程池
     */
    public static ThreadPoolExecutor getThreadPoolByName(String threadPoolName) {
        return threadPoolExecutorMap.get(threadPoolName);
    }
}
